package com.spring.security.client.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.security.core.properties.SecurityConstants;
import com.spring.security.core.support.ServerResponseEntity;
import com.spring.security.core.validate.exception.ValidateCodeException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Strategy used to handle a failed authentication attempt.
 * <p>
 * Typical behaviour might be to redirect the user to the authentication page (in the case
 * of a form login) to allow them to try again. More sophisticated logic might be
 * implemented depending on the type of the exception. For example, a
 * {@link CredentialsExpiredException} might cause a redirect to a web controller which
 * allowed the user to change their password.
 *
 * @author seabed_moon
 */
@Log4j2
@Component("sunLandAuthenticationFailureHandler")
public class SpringAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     *                  request.
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("LOGIN FAILURE");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        if(exception instanceof ValidateCodeException){
            response.getWriter().write(objectMapper.writeValueAsString(ServerResponseEntity.fail(((ValidateCodeException) exception).getCode(), exception.getMessage(), "")));
        }else {
            response.getWriter().write(objectMapper.writeValueAsString(ServerResponseEntity.fail(HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), "")));
        }
        String originHeader = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", originHeader);
        response.addHeader("Access-Control-Allow-Headers", SecurityConstants.DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS);
        response.addHeader("Access-Control-Allow-Credentials", SecurityConstants.DEFAULT_ACCESS_CONTROL_ALLOW_CREDENTIALS);
        response.setHeader("Access-Control-Allow-Methods", SecurityConstants.DEFAULT_ACCESS_CONTROL_ALLOW_METHODS);
    }
}
